package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.service.OssService;
import com.atguigu.srb.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import java.util.UUID;
@Service
public class OssServiceImpl  implements OssService {
    @Override
    public String uploadImage(MultipartFile file, String module) {
        OSS ossClient = new OSSClientBuilder().
                build(OssProperties.ENDPOINT,OssProperties.KEY_ID,OssProperties.KEY_SECRET);
        //判断 如果桶不存在创建新桶
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            //设置为公有读
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        //获取文件后缀名
        String filenameExtension =
                StringUtils.getFilenameExtension(file.getOriginalFilename());
        //文件夹 每日更新
        String folder = new DateTime().toString("yyyy/MM/dd");
        //文件名随机生成
        String fileName = UUID.randomUUID().toString();
        //拼接Key
        String key = module+"/"+folder+"/"+fileName+"."+filenameExtension;
        //将文件上传到阿里云
        try {
            ossClient.putObject(OssProperties.BUCKET_NAME,key,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key;
        ossClient.shutdown();
        return url;

    }

    @Override
    public void deleteImage(String url) {
        OSS ossClient =
                new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID,OssProperties.KEY_SECRET);
        String key = url.substring(("https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/").length());
        ossClient.deleteObject(OssProperties.BUCKET_NAME,key);

    }
}
